---
title: 升级 Http2 🌐
description: Feat Http2
sidebar:
    order: 6
---

import http2_architecture from './img/http2_architecture.svg';
import CheckAuthorize from '../../../components/CheckAuthorize.astro'

<CheckAuthorize/>

Feat 支持通过 **HttpRequest.upgrade** 方法将 HTTP/1.1 连接升级到 HTTP/2 协议。
<img src={http2_architecture.src} alt="HTTP/2协议栈" width="80%"/>

## 快速开始
操作示例如下：
```java title=Http2Demo.java
public class Http2Demo {
    public static void main(String[] args) {
        Feat.httpServer().httpHandler(request -> {
            request.upgrade(new Http2Upgrade() {
                @Override
                public void handle(HttpRequest http2Request) {
                    HttpResponse response = http2Request.response();
                    response.setStatus(200);
                    response.send("HTTP/2响应");
                }
            });
        }).listen();
    }
}
```

## 核心机制
1. **协议协商**：通过`Connection: Upgrade`和`Upgrade: h2c`头部完成握手
2. **多路复用**：基于Stream ID实现请求并发处理
3. **头部压缩**：采用HPACK算法压缩请求头
4. **服务端推送**：通过PushBuilder实现资源预推送

## 配置参数
Http2Upgrade 提供以下构造方法：
```java
public Http2Upgrade() {
    this(120000); // 默认空闲超时120秒
}

public Http2Upgrade(long idleTimeout) {
    this.idleTimeout = idleTimeout;
}
```

## 性能优化
1. 启用HPACK压缩：初始化时设置`enableHeaderCompression=true`
2. 调整流控窗口：通过`Http2Settings.initialWindowSize(1048576)`
3. 服务端推送配置：
```java
http2Request.push()
    .path("/static/style.css")
    .send();
```
4. 保持长连接：设置合理的`idleTimeout`值



